package edu.mju.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.mju.admin.entity.SysUser;
import edu.mju.admin.service.SysPermissionService;
import edu.mju.admin.service.SysUserService;
import edu.mju.security.entity.SecurityUser;
import edu.mju.security.entity.Users;
import edu.mju.servicebasic.exception.TravelException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * 自定义UserDetailsService
 */
@Service(value = "userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService aclUserService;

    @Autowired
    private SysPermissionService aclPermissionService;

    /**
     * 根据用户名查询数据
     * @param username 用户名
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        SysUser one = aclUserService.getOne(queryWrapper);
        if(ObjectUtils.isEmpty(one)){
           throw new TravelException(40000,"用户不存在！");
        }

        //spring_security中的users实体类
        Users aclUser = new Users();
        //复制
        BeanUtils.copyProperties(one,aclUser);

        //根据用户信息 查询权限列表
        List<String> permissionList = aclPermissionService.selectPermissionValueByUserId(one.getId());
        SecurityUser securityUser = new SecurityUser(aclUser);
        securityUser.setPermissionList(permissionList);
        return securityUser;
    }
}
